﻿//-----------------------------------------------------------------------
// <copyright file="ThreadedDictionary.CS" company="FastNET Services">
//     Copyright (c) 2008-2009. All Rights Reserved.
// </copyright>
// <license>
//     GPLv2
// </license>
// <warranty>
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
//     BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//     NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
//     DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </warranty>
//-----------------------------------------------------------------------
#region Usings

using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using GateShift.Services.SDK.Threading.Locking;

#endregion

/*
 * SOURCES:
 * http://devplanet.com/blogs/brianr/archive/2008/09/26/thread-safe-dictionary-in-net.aspx
 */

namespace GateShift.Services.SDK.Threading
{
    /// <summary>
    /// Common class used to simplify threading using a dictionary for storage
    /// </summary>
    /// <typeparam name="TKey">Type of the key to use</typeparam>
    /// <typeparam name="TValue">Type of the value to use</typeparam>
    [Serializable]
    public class ThreadedDictionary<TKey, TValue> : IThreadedDictionary<TKey, TValue>
    {
        // This is the internal dictionary that we are wrapping
        private readonly IDictionary<TKey, TValue> baseCollection;

        [NonSerialized]
        private readonly ReaderWriterLockSlim dictionaryLock;

        /// <summary>
        /// Initializes a new instance of the ThreadedDictionary class
        /// </summary>
        public ThreadedDictionary()
        {
            baseCollection = new Dictionary<TKey, TValue>();
            dictionaryLock = Locks.GetLockInstance(LockRecursionPolicy.NoRecursion);
        }

        /// <summary>
        /// Gets a collection of all keys in the collection
        /// </summary>
        public virtual ICollection<TKey> Keys
        {
            get
            {
                using (new ReadOnlyLock(dictionaryLock))
                {
                    return new List<TKey>(baseCollection.Keys);
                }
            }
        }

        /// <summary>
        /// Gets a collection of all values in the collection
        /// </summary>
        public virtual ICollection<TValue> Values
        {
            get
            {
                using (new ReadOnlyLock(dictionaryLock))
                {
                    return new List<TValue>(baseCollection.Values);
                }
            }
        }

        /// <summary>
        /// Gets the count of items from the dictionary
        /// </summary>
        public virtual int Count
        {
            get
            {
                using (new ReadOnlyLock(dictionaryLock))
                {
                    return baseCollection.Count;
                }
            }
        }

        /// <summary>
        /// Gets a value indicating whether or not the dictionary is read only
        /// </summary>
        public virtual bool IsReadOnly
        {
            get
            {
                using (new ReadOnlyLock(dictionaryLock))
                {
                    return baseCollection.IsReadOnly;
                }
            }
        }

        /// <summary>
        /// Indexer used to get or set an item by it's key
        /// </summary>
        /// <param name="key">Key to lookup on</param>
        /// <returns>Value associated with key</returns>
        public virtual TValue this[TKey key]
        {
            get
            {
                using (new ReadOnlyLock(dictionaryLock))
                {
                    return baseCollection[key];
                }
            }

            set
            {
                using (new WriteLock(dictionaryLock))
                {
                    baseCollection[key] = value;
                }
            }
        }

        /// <summary>
        /// Copies this dictionary to the specified array of items
        /// </summary>
        /// <param name="array">KeyValuePare to copy to</param>
        /// <param name="arrayIndex">Index to start copying from</param>
        public virtual void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
        {
            using (new ReadOnlyLock(dictionaryLock))
            {
                baseCollection.CopyTo(array, arrayIndex);
            }
        }

        #region Information

        /// <summary>
        /// Checks whether or not the specified pair is contained inside the dictionary
        /// </summary>
        /// <param name="item">KeyValuePair with the data to check</param>
        /// <returns>Boolean whether or not the item is inside the dictionary</returns>
        public virtual bool Contains(KeyValuePair<TKey, TValue> item)
        {
            using (new ReadOnlyLock(dictionaryLock))
            {
                return baseCollection.Contains(item);
            }
        }

        /// <summary>
        /// Checks whether or not the specified Key is contained inside the dictionary
        /// </summary>
        /// <param name="key">Key with the data to check</param>
        /// <returns>Boolean whether or not the item is inside the dictionary</returns>
        public virtual bool ContainsKey(TKey key)
        {
            using (new ReadOnlyLock(dictionaryLock))
            {
                return baseCollection.ContainsKey(key);
            }
        }

        #endregion

        #region Modification

        /// <summary>
        /// This is a blind remove. Prevents the need to check for existence first.
        /// </summary>
        /// <param name="key">Key to remove</param>
        public void RemoveSafe(TKey key)
        {
            using (new ReadLock(dictionaryLock))
            {
                if (!baseCollection.ContainsKey(key))
                {
                    return;
                }

                using (new WriteLock(dictionaryLock))
                {
                    baseCollection.Remove(key);
                }
            }
        }

        /// <summary>
        /// Merge is similar to the SQL merge or upsert statement.  
        /// </summary>
        /// <param name="key">Key to lookup</param>
        /// <param name="newValue">New Value to add</param>
        public void MergeSafe(TKey key, TValue newValue)
        {
            using (new WriteLock(dictionaryLock)) // take a writelock immediately since we will always be writing
            {
                if (baseCollection.ContainsKey(key))
                {
                    baseCollection.Remove(key);
                }

                baseCollection.Add(key, newValue);
            }
        }

        /// <summary>
        /// Removes an item by its specified key
        /// </summary>
        /// <param name="key">Key to remove</param>
        /// <returns>Boolean whether or not the item was removed</returns>
        public virtual bool Remove(TKey key)
        {
            using (new WriteLock(dictionaryLock))
            {
                return baseCollection.Remove(key);
            }
        }

        /// <summary>
        /// Clears the dictionary of all items
        /// </summary>
        public virtual void Clear()
        {
            using (new WriteLock(dictionaryLock))
            {
                baseCollection.Clear();
            }
        }

        /// <summary>
        /// Adds the specified item to the collection
        /// </summary>
        /// <param name="item">KeyValuePair to add</param>
        public virtual void Add(KeyValuePair<TKey, TValue> item)
        {
            using (new WriteLock(dictionaryLock))
            {
                baseCollection.Add(item);
            }
        }

        /// <summary>
        /// Adds the specified item to the collection
        /// </summary>
        /// <param name="key">Key of the item</param>
        /// <param name="value">New value to add</param>
        public virtual void Add(TKey key, TValue value)
        {
            using (new WriteLock(dictionaryLock))
            {
                baseCollection.Add(key, value);
            }
        }

        /// <summary>
        /// Removes an item from the collection
        /// </summary>
        /// <param name="item">Item to remove</param>
        /// <returns>Boolean whether or not the item was removed</returns>
        public virtual bool Remove(KeyValuePair<TKey, TValue> item)
        {
            using (new WriteLock(dictionaryLock))
            {
                return baseCollection.Remove(item);
            }
        }

        #endregion

        #region Navigation

        /// <summary>
        /// Trys to get an item from the dictionary with the specified key
        /// </summary>
        /// <param name="key">Key to use when looking up an item</param>
        /// <param name="value">Value found or default of the value type if not found (Out)</param>
        /// <returns>Boolean whether or not the item was found</returns>
        public virtual bool TryGetValue(TKey key, out TValue value)
        {
            using (new ReadOnlyLock(dictionaryLock))
            {
                return baseCollection.TryGetValue(key, out value);
            }
        }

        #endregion

        #region IEnumerable

        /// <summary>
        /// Not Supported
        /// </summary>
        /// <returns>Throws NotSupportedException</returns>
        public virtual IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
        {
            throw new NotSupportedException("Cannot enumerate a threadsafe dictionary.  Instead, enumerate the keys or values collection");
        }

        /// <summary>
        /// Not Supported
        /// </summary>
        /// <returns>Throws NotSupportedException</returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            throw new NotSupportedException("Cannot enumerate a threadsafe dictionary.  Instead, enumerate the keys or values collection");
        }

        #endregion
    }
}